package edu.cuit.zhuyimeng.flight.service.impl;

import com.baomidou.dynamic.datasource.annotation.Master;
import edu.cuit.zhuyimeng.flight.controller.vo.FlightInfoVO;
import edu.cuit.zhuyimeng.flight.service.IJobDispatchService;
import edu.cuit.zhuyimeng.framework.common.util.TimeUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tech.powerjob.client.PowerJobClient;
import tech.powerjob.common.enums.ExecuteType;
import tech.powerjob.common.enums.ProcessorType;
import tech.powerjob.common.enums.TimeExpressionType;
import tech.powerjob.common.request.http.SaveJobInfoRequest;
import tech.powerjob.common.response.ResultDTO;

import java.util.Calendar;
import java.util.Date;

/**
 * 调度任务管理服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class JobDispatchService implements IJobDispatchService {

    private final PowerJobClient powerJobClient;

    @Override
    @Master
    public ResultDTO<Long> startReleaseTicketJob(FlightInfoVO flightInfo) {
        SaveJobInfoRequest saveJobInfoRequest = new SaveJobInfoRequest();
        saveJobInfoRequest.setJobName("开放航班 " + flightInfo.getNumber() + " 订票接口");
        saveJobInfoRequest.setJobDescription("自动开放接口，开放后用户可以订票");

        saveJobInfoRequest.setTimeExpressionType(TimeExpressionType.CRON);
        saveJobInfoRequest.setTimeExpression(TimeUtils.getCron(flightInfo.getStartBook()));

        saveJobInfoRequest.setExecuteType(ExecuteType.STANDALONE);
        saveJobInfoRequest.setProcessorType(ProcessorType.BUILT_IN);
        saveJobInfoRequest.setProcessorInfo("releaseTicketProcessor");

        saveJobInfoRequest.setJobParams(String.valueOf(flightInfo.getId()));

        return powerJobClient.saveJob(saveJobInfoRequest);
    }

    @Override
    @Master
    public ResultDTO<Long> startDestroyFlightJob(Long flightId) {
        SaveJobInfoRequest saveJobInfoRequest = new SaveJobInfoRequest();
        saveJobInfoRequest.setJobName("销毁ID为 " + flightId + " 的航班");
        saveJobInfoRequest.setJobDescription("自动销毁航班");

        saveJobInfoRequest.setTimeExpressionType(TimeExpressionType.CRON);
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.HOUR,2);
        saveJobInfoRequest.setTimeExpression(TimeUtils.getCron(instance.getTime()));

        saveJobInfoRequest.setExecuteType(ExecuteType.STANDALONE);
        saveJobInfoRequest.setProcessorType(ProcessorType.BUILT_IN);
        saveJobInfoRequest.setProcessorInfo("destroyFlightProcessor");

        saveJobInfoRequest.setJobParams(String.valueOf(flightId));

        return powerJobClient.saveJob(saveJobInfoRequest);
    }
}
